import { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as cartActions from '../store/actions/cart.actions'

class Cart extends Component {
  componentDidMount() {
    const { loadCarts } = this.props
    loadCarts()
  }
  // 修改购物车商品数量
  changeProductNumber(cid, e) {
    const count = e.target.value
    // 向服务器端发送请求，修改购物车商品数量
    this.props.changeServiceProductNumber({cid, count})
  }
  render() {
    const { carts, deleteProductFromCart } = this.props
    console.log(carts)
    return (
      <section className='container content-section'>
        <h2 className='section-header'>购物车</h2>
        <div className='cart-row'>
          <span className='cart-item cart-header cart-column'>商品</span>
          <span className='cart-price cart-header cart-column'>价格</span>
          <span className='cart-quantity cart-header cart-column'>数量</span>
        </div>
        <div className='cart-items'>
          {carts.map(item => 
              (<div className='cart-row' key={item.id}>
              <div className='cart-item cart-column'>
                <img 
                  className='cart-item-image' 
                  src={`http://localhost:3005/${item.thumbnail}`} 
                  width='100' 
                  height='100' 
                  alt='' />
                <span className='cart-item-title'>{item.title}</span>
              </div>
              <span className='cart-price cart-column'>￥{item.price}</span>
              <div className='cart-quantity cart-column'>
                <input 
                  className='cart-quantity-input' 
                  type='number' 
                  value={item.count} 
                  onChange={e => this.changeProductNumber(item.id, e)} />
                <button 
                  className='btn btn-danger' 
                  type='button' 
                  onClick = {() => deleteProductFromCart(item.id)}>
                  删除
                </button>
              </div>
            </div>))}
        </div>
        <div className='cart-total'>
          <strong className='cart-total-title'>总价</strong>
          <span className='cart-total-price'>￥{carts.reduce((pre, cur) => {
            return pre + cur.price * cur.count
          }, 0)}</span>
        </div>
      </section>
    )
  }
}

const mapStateToProps = state => ({
  carts : state.carts
})

const mapDispatchToProps = dispatch => bindActionCreators(cartActions, dispatch)

export default connect(mapStateToProps, mapDispatchToProps)(Cart)
